using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Impact.Web.Admin
{
    /// <summary>
    /// code-behind for the user editing page
    /// </summary>
    public partial class EditUser : System.Web.UI.Page
    {
        /// <summary>
        /// override for OnLoad to perform startup functionality
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            string username = Request.QueryString["username"];

            if (!IsPostBack)
            {
                MembershipUser user;
                if (!string.IsNullOrEmpty(username))
                {
                    user = Membership.GetUser(username);
                    this._userName.Text = user.UserName;
                    this._email.Text = user.Email;

                    this._passwordPanel.Visible = false;
                    this._passwordRequired.Enabled = false;
                    this._passwordValidation.Enabled = false;
                }
            }

            password.TargetUrl = string.Format("ChangePassword.aspx?username={0}", username);

        }

        /// <summary>
        /// event handler fired when the user clicks submit
        /// </summary>
        protected void SubmitCommand(object sender, EventArgs e)
        {
            MembershipUser user = Membership.GetUser(this._userName.Text);
            if (user == null) // new user
            {
                MembershipCreateStatus status;
                Membership.CreateUser(_userName.Text, _password.Text, _email.Text, "question", "answer", true, out status);

                if (status != MembershipCreateStatus.Success)
                {
                    throw new ApplicationException(string.Format("User creation failed: {0}", status.ToString()));
                }
            }
            else
            {
                user.Email = this._email.Text;
                Membership.UpdateUser(user);
            }

            Return();
        }

        /// <summary>
        /// event handler fired when the user clicks cancel
        /// </summary>
        protected void CancelCommand(object sender, EventArgs e)
        {
            Return();
        }

        /// <summary>
        /// return the user to the users listing page
        /// </summary>
        private void Return()
        {
            Response.Redirect("Users.aspx");
        }

    }
}
